package com.rongc.client.freight.base.view.widget.CJRow;

import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;

import com.rongc.client.core.log.CCLog;
import com.rongc.client.core.utils.SystemUtil;
import com.rongc.client.freight.utils.dic.impl.Table;


public class CJRow extends AdapterView<ListAdapter> {
	private final static String TAG = "MyViewGroup";
	private boolean mDataChanged = false;
	private boolean mIsDataChangedUseful = true;
	protected CustomCJRowAdapter mAdapter;
	protected int mCurrentX;
//	private Queue<View> mRemovedViewQueue = new LinkedList<View>();
	private int lineHeight = 0;
	private int groupHeight = 0;
	
	Activity activity;
	ARResponse response = null;
	Table table = null;
	int layoutID;
	int[] elementIDs;
	
	public Drawable bgtop;
	public Drawable bgbottom;
	public Drawable bgcenter;
	public Drawable bgsingle;
	public boolean hascorner;
	
	public CJRow(Context context) {
		super(context);
		init();
	}
	
	public CJRow(Context context, AttributeSet attrs) {
		super(context, attrs);
		lineHeight = SystemUtil.dip2px(context,1);
		groupHeight = SystemUtil.dip2px(context,4);
		/*TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CJRow);
		hascorner = a.getBoolean(R.styleable.CJRow_hascorner, false);
		mIsDataChangedUseful = a.getBoolean(R.styleable.CJRow_datachange, true);
		bgtop = context.getResources().getDrawable(a.getResourceId(R.styleable.CJRow_bgtop, R.drawable.cj_all_listbg_top));
		bgbottom = context.getResources().getDrawable(a.getResourceId(R.styleable.CJRow_bgbottom, R.drawable.cj_all_listbg_down));
		bgcenter = context.getResources().getDrawable(a.getResourceId(R.styleable.CJRow_bgcenter, R.drawable.cj_all_listbg_middle));
		bgsingle = context.getResources().getDrawable(a.getResourceId(R.styleable.CJRow_bgsingle, R.drawable.default_selector));
		a.recycle();*/
	}
	
	
	void init(){
		hascorner = true;
		/*bgtop = getResources().getDrawable(R.drawable.cj_all_listbg_top);
		bgbottom = getResources().getDrawable(R.drawable.cj_all_listbg_down);
		bgcenter = getResources().getDrawable(R.drawable.cj_all_listbg_middle);
		bgsingle = getResources().getDrawable(R.drawable.default_selector);*/
	}
	
	
	// 容器宽高
	int specSize_Widht, specSize_Heigth;
	@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        specSize_Widht = measureWidth(widthMeasureSpec) ;  
        specSize_Widht = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec) ;  
        CCLog.e("ccqx", "onMeasure"+specSize_Widht+"getChildCount"+getChildCount()+mDataChanged);
        if(mDataChanged || !mIsDataChangedUseful){
        	removeAllViewsInLayout();
        	mDataChanged = false;
        }
        if(getChildCount() == 0 && mAdapter != null){
        	childheight = 0;
	        for (int index = 0; index < mAdapter.getCount(); index++) {
//	            final View child = mAdapter.getView(index, mRemovedViewQueue.poll(), this);
	            final View child = mAdapter.getView(index, null, this);
	            if(child.getVisibility() != View.GONE)
	            	addAndMeasureChild(child , -1);
	        }
        }

        specSize_Heigth = measureHeigth(heightMeasureSpec) ;

        setMeasuredDimension(specSize_Widht , specSize_Heigth) ; 
        
    }
	
    private int measureWidth(int widthMeasureSpec){
    	int measure_mode = MeasureSpec.getMode(widthMeasureSpec) ;  
    	int measure_size = MeasureSpec.getSize(widthMeasureSpec) ;  
//    	if(measure_mode == MeasureSpec.EXACTLY){
    		measure_size = measure_size > childwidth ? measure_size : childwidth;
    		CCLog.print("measureWidth  --- EXACTLY"+measure_size);
//    	}else if(measure_mode == MeasureSpec.AT_MOST){
//    		measure_size = childwidth;
//    		CCLog.print("measureWidth  --- AT_MOST"+measure_size);
//    	}else if(measure_mode == MeasureSpec.UNSPECIFIED){
//    		CCLog.print("measureWidth  --- UNSPECIFIED"+measure_size);
//    	}
    	return measure_size;
    }
    
    private int measureHeigth(int heigthMeasureSpec){
    	if(mAdapter == null)
    		return 0;
	    	int measure_mode = MeasureSpec.getMode(heigthMeasureSpec) ;  
	    	int measure_size = MeasureSpec.getSize(heigthMeasureSpec) ;  
	    	
	    	if(measure_mode == MeasureSpec.EXACTLY){
	    		CCLog.print("MeasureSpec.EXACTLY"+measure_size);
	    	}else if(measure_mode == MeasureSpec.AT_MOST){
	    		CCLog.print("MeasureSpec.AT_MOST"+measure_size);
	    		measure_size = childheight * mAdapter.getCount();
	    	}else if(measure_mode == MeasureSpec.UNSPECIFIED){
	    		CCLog.print("UNSPECIFIED"+measure_size);
	    	}
    	
//	    for (int i = 0; i < getChildCount(); i++) {
//	    	View child = getChildAt(i);
//	    	childheight = child.getMeasuredHeight();
//		}	

    	return childheight + ((MarginLayoutParams)getLayoutParams()).topMargin + ((MarginLayoutParams)getLayoutParams()).bottomMargin + (mAdapter.getCount() - 1) * lineHeight + (mAdapter.getGroupCount() - 1) * groupHeight;
    }
    
    private void addAndMeasureChild(final View child, int viewPos) {
		LayoutParams params = child.getLayoutParams();
		if(params == null) {
			params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}
		addViewInLayout(child, viewPos, params, true);
//		CCLog.e("ccqx","addAndMeasureChild"+specSize_Widht);
		child.measure(MeasureSpec.makeMeasureSpec(specSize_Widht, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY));
		childheight += child.getMeasuredHeight();
		childwidth =  child.getMeasuredWidth();
	}
    
 
    int childheight ,childwidth;
    
    @Override
    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
	    	int lengthY = 0;
	        final int count = getChildCount();
			int groupId = -99;
	        for(int i=0;i<count;i++){
	            final View child = this.getChildAt(i);
	            int width = child.getMeasuredWidth();
	            int height = child.getMeasuredHeight();
	            int lengthX = width;
//	            int lengthY = (i + 1)*(height)+ i * lineHeight;
	            if(i == 0)
	            	lengthY = height;
	            else
	            	lengthY += height + lineHeight;


				if(mAdapter.getGroupCount() > 1){
					if(groupId != mAdapter.getGroup(i)) {
						lengthY += groupHeight;
						groupId = mAdapter.getGroup(i);
					}
				}
	            child.layout(lengthX-width, lengthY-height, lengthX, lengthY);
	            CCLog.print("onlayout"+child.getId() + "lengthY"+lengthY);
//	            if(mRemovedViewQueue.size() < getChildCount())
//	            	mRemovedViewQueue.offer(child);  
	        }
	        
	    }
	
//	@Override
//	public ListAdapter getAdapter() {
//		return mAdapter;
//	}

	@Override
	public View getSelectedView() {
		return null;
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
//		if(mAdapter != null) {
//			mAdapter.unregisterDataSetObserver(mDataObserver);
//		}
		mAdapter =  (CustomCJRowAdapter) adapter;
		mAdapter.registerDataSetObserver(mDataObserver);
		
		invalidate();
		requestLayout();
	}

	@Override
	public void setSelection(int position) {
		
	}

	private DataSetObserver mDataObserver = new DataSetObserver() {

		@Override
		public void onChanged() {
			CCLog.print("onChanged");
			synchronized(CJRow.this){
				mDataChanged = true;
			}
			invalidate();
			requestLayout();
		}

		@Override
		public void onInvalidated() {
			CCLog.print("onInvalidated");
			invalidate();
			requestLayout();
		}
		
	};
	
	public void setData(Activity activity, Table table, ARResponse response) {
		this.activity = activity;
		this.table = table;
		this.response = response;
		if (response != null) {
			mAdapter = new CustomCJRowAdapter(activity, this, this.table, this.response);
		} 
		
		setAdapter(mAdapter);
	}
	
	public void setData(Activity activity, Table table, ARResponse response,
			int layoutID, int[] elementIDs) {
		this.activity = activity;
		this.elementIDs = elementIDs;
		this.layoutID = layoutID;
		this.table = table;
		this.response = response;
		if (response != null) {
			mAdapter = new CustomCJRowAdapter(activity, this, this.table, this.response,
					layoutID, elementIDs);
		} 

		setAdapter(mAdapter);
		getAdapter().notifyDataSetChanged();
	}
	
	/*public void setData(Activity activity, Table table, ARResponse response,
			int layoutID, int[] elementIDs) {
		this.activity = activity;
		this.elementIDs = elementIDs;
		this.layoutID = layoutID;
		this.table = table;
		this.response = response;
		if (response != null) {
			mAdapter = new CJRowAdapter(activity, this, table, this.response,
					layoutID, elementIDs);
		} else {
			loadByTable();
			mAdapter = new CJRowAdapter(activity, this, table, this.response,
					layoutID, elementIDs);
		}

		setAdapter(mAdapter);
	}
	
	public void setData(Activity activity, Table table, ARResponse response,
			int layoutID, int[] elementIDs, int height) {
		getLayoutParams().height = height;
		this.setData(activity, table, response, layoutID, elementIDs);
	}
	
	
	public void loadByTable() {
		String[] fieldList = new String[table.getFieldList().size()];
		int i = 0;
		for (Field field : table.getFieldList()) {
			fieldList[i] = field.getFieldName();
			i++;
		}
		ArrayList<String[]> valueList = new ArrayList<String[]>();
		try {
			response = ARResponseTool.toResponse(fieldList, valueList);
		} catch (JSONException e) {

		}
	}
	
	*//**
	 * 刷新界面
	 * 
	 * @param response
	 *//*
	public void refresh() {
		getAdapter().notifyDataSetChanged();
	}

	

	*//**
	 * 传入新的table并刷新界面
	 * 
	 * @param table
	 *//*
	public void refresh(Table table) {
		this.table = table;
		if(response!=null){
			refresh(response);
		}
	}
	
	*//**
	 * 传入新的Response和table并刷新界面
	 * 
	 * @param response
	 *//*
	public void refresh(Table table, ARResponse response) {
		this.table = table;
		refresh(response);
	}*/
	
	/**
	 * 传入新的Response并刷新界面
	 * 
	 * @param response
	 */
	public void refresh(ARResponse response) {
		this.response = response;
		if (response != null) {
			setData(activity, table, this.response, layoutID, elementIDs);
		}
		getAdapter().notifyDataSetChanged();
	}

	// 根据位置修改值
	public void setValue(int position, String value) {
		getAdapter().setFieldvalue(position, value);
		getAdapter().notifyDataSetChanged();
	}

	// 根据字段名修改值
	public void setValue(String fieldName, String value) {
		getAdapter().setFieldvalue(fieldName, value);
		getAdapter().notifyDataSetChanged();
	}
	
	/**
	 * 获取CJROW的适配器
	 * 
	 * @return CJRowAdapter
	 */
	public CustomCJRowAdapter getAdapter() {
		return mAdapter;
	}

	/**
	 * 设置项监听
	 * 
	 * @param listener
	 */
	public void setCJRowListener(CJRowListener listener) {
			try {
				getAdapter().setCJRowListener(listener);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}

	/**
	 * 设置项绑定
	 * @param binder
	 */
	public void setViewBinder(ViewBinder binder) {
			try {
				getAdapter().setViewBinder(binder);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public void setLableBinder(ViewBinder binder) {
			getAdapter().setLableBinder(binder);
	}
}
